import {
	baseURL
} from '@/config/config'


function getRect(selector, all, that) {
	return new Promise(resolve => { //获取窗口位置，滚动位置信息
		uni.createSelectorQuery()
			// .in(that)
			.selectViewport().scrollOffset()[all ? 'selectAll' : 'select'](selector)
			.boundingClientRect()
			.exec(rect => {
				if (all && Array.isArray(rect) && rect.length) {
					resolve(rect);
				}
				if (!all && rect) {
					resolve(rect);
				}
			});
	});
}

function getRectInfo(selector, all = false, that) { //显示元素内容信息 值为undefined时会使用默认值
	return new Promise(resolve => {
		let element = uni.createSelectorQuery()
		if (that) {
			element.in(that) //组件内部需传递组件内部this
		}
		element[all ? 'selectAll' : 'select'](selector).boundingClientRect(rect => {
				if (all && Array.isArray(rect) && rect.length) {
					resolve(rect);
				}
				if (!all && rect) {
					resolve(rect);
				}
			})
			.exec();
	});
}

function initPhone(phone) { // 手机号隐藏四位
	var phone = phone.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
	return phone
}

function initPriceChild(price) { //单个处理
	var price = price.toLocaleString();
	return price
}

function initIdentity(id) { //身份证号隐藏12位
	var newId = id.replace(/(\d{3})\d{12}(\d{2})/, "$1************$2");
	return newId;
}

function upfileImag(data, callBack) {
	let opitons = {
		url: 'file/image/upload',
		name: 'imageFile',
		count: 1,
	}
	if (typeof data == 'function') {
		callBack = data
	} else {
		opitons = {
			...opitons,
			...data
		}
	}
	selectImag()

	function selectImag() {
		// #ifdef MP-WEIXIN
		uni.chooseMedia({
			mediaType: "image",
			count: opitons.count,
			success(chooseImageRes) {
				const tempFilePaths = chooseImageRes.tempFiles;
				//判断是否可以图片上传
				let upStatus = (callbackFn) => {
					return tempFilePaths.some(callbackFn)
				}

				if (upStatus((tempItem) => (tempItem.size / 1024 / 1024) > 10)) {
					return uni.showToast({
						title: '请上传2M以内的图片。',
						icon: 'none',
						mask: true
					})
				}
				if (upStatus((tempItem) => {
						return 2 < (tempItem.size / 1024 / 1024) && (tempItem.size / 1024 / 1024) <
							10
					})) {
					return uni.showModal({
						title: '提示',
						content: '您上传的图片太大了，继续上传会被自动压缩导致不清晰。',
						confirmText: '更换',
						cancelText: '继续',
						success: (res) => {
							if (res.confirm) {
								selectImag()
							} else if (res.cancel) {
								getAllImages(tempFilePaths)
							}
						}
					});
				}
				getAllImages(tempFilePaths)
				// upImg(tempFilePaths, callBack)
			}
		})
		// #endif
	}

	function getAllImages(tempFilePaths) {
		uni.showLoading({
			title: '上传中...',
		})
		// 图片多张上传优化
		Promise.all(tempFilePaths.map(tempItem => upImg(tempItem.tempFilePath))).then(res => {
			uni.hideLoading()
			if (opitons.name !== 'imageFile') { //身份证上传是返回请求结果
				return callBack(res[0].data)
			}
			//过滤点上传失败的图片
			let imgArry = res.filter(imgItem => imgItem.code === 200)
			//返回数组集合
			callBack(imgArry.map(imgObj => imgObj.data))

		}).catch(res => {
			uni.showToast({
				title: '图片上传失败，请重试',
				icon: 'none'
			})
			uni.hideLoading()
		})
	}

	function upImg(tempFilePath) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseURL + opitons.url, //仅为示例，非真实的接口地址
				filePath: tempFilePath,
				name: opitons.name,
				fileType: "image",
				header: {
					"Content-Type": "multipart/form-data"
				},
				success: (uploadFileRes) => {
					if (uploadFileRes.statusCode !== 200) {
						uni.showToast({
							title: '图片上传太大了',
							icon: 'none'
						})
						return resolve()
					}
					resolve(JSON.parse(uploadFileRes.data))
					// callBack(JSON.parse(uploadFileRes.data))
				},
				fail() {
					reject()
				}
			})
		})
	}
}

// js 精度计算

//加法运算
function floatAdd(arg1, arg2) {
	let r1, r2, m
	try {
		r1 = arg1.toString().split('.')[1].length
	} catch (e) {
		r1 = 0
	}
	try {
		r2 = arg2.toString().split('.')[1].length
	} catch (e) {
		r2 = 0
	}
	m = Math.pow(10, Math.max(r1, r2))
	return Number((arg1 * m + arg2 * m) / m)
}

// 减法运算
function floatSub(arg1, arg2) {
	let r1, r2, m, n
	try {
		r1 = arg1.toString().split('.')[1].length
	} catch (e) {
		r1 = 0
	}
	try {
		r2 = arg2.toString().split('.')[1].length
	} catch (e) {
		r2 = 0
	}
	m = Math.pow(10, Math.max(r1, r2))
	// 动态控制精度长度
	n = (r1 >= r2) ? r1 : r2
	return Number(((arg1 * m - arg2 * m) / m).toFixed(n))
}
export default {
	getRect,
	getRectInfo,
	initPhone,
	initPriceChild,
	initIdentity,
	upfileImag,
	floatAdd,
	floatSub,
}